﻿using System;
using System.Web.Http;
using System.Collections.Specialized;
using PreeRegisterModel;
using PreeRegisterBLL;
using PreeRegisterBLL.Security;
using System.Threading;
using Newtonsoft.Json.Linq;

namespace PreeRegister_WebAPI.Controllers
{
    public class payController : ApiController
    {
        static bool done;
        static object locker = new object();
        [HttpPost]
        /// <summary>
        /// 支付结果通知
        /// </summary>
        /// <param name="any"></param>
        /// <returns></returns>
        public EncodeModel result(NameValueCollection any)
        {
            try
            {
                return PayResult();
            }
            catch (Exception err)
            {
                PayResultResponseItemModel payResultResponseItemModel = new PayResultResponseItemModel();
                payResultResponseItemModel.code = "-1000";
                payResultResponseItemModel.msg = "通知医院支付结果异常：" + err.ToString();
                //序列化返回内容类
                string ReturnBodyJson = csSerialize.PayResultResponseItemModel(payResultResponseItemModel);

                //返回参数日志
                CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "1：通知医院支付结果返回参数：\r\n" + CommonBLL.ConvertJsonString(ReturnBodyJson.ToString()));

                //加密返回内容Json
                return ResultDecode.EncodeResult(ReturnBodyJson);
            }
        }
        private static EncodeModel PayResult()
        {
            string ReturnBodyJson = "";
            lock (locker)
            {
                if (!done)
                {
                    //获取JSON加密参数
                    string jsonData = CommonBLL.RequestGetParam("jsonData").ToString();

                    PayResultResponseItemModel payResultResponseItemModel = new PayResultResponseItemModel();

                    //解密头和内容信息
                    string head_json = "";
                    string body_json = "";
                    string head_json_encode = "";
                    string body_json_encode = "";
                    head_json_encode = head_json = CommonBLL.RequestGetParam("head").ToString();
                    body_json_encode = body_json = CommonBLL.RequestGetParam("body").ToString();

                    jsonData += "{";
                    jsonData += string.Format("\"head\":\"{0}\",\"body\":\"{1}\"", head_json, body_json);
                    jsonData += "}";
                    string ErrMsg = "";
                    if (!ResultDecode.DecodeResult(jsonData, "pay|result", ref head_json, ref body_json, ref ErrMsg))
                    {
                        //序列化返回内容类
                        ReturnBodyJson = csSerialize.PayResultResponseItemModel(payResultResponseItemModel);

                        //加密返回内容Json
                        return ResultDecode.EncodeResult(ReturnBodyJson);
                    }

                    //入口参数日志
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "通知医院支付结果请求参数：\r\n" + CommonBLL.ConvertJsonString(body_json.ToString()));

                    //反序列化请求字符串
                    PayResultRequstModel notPayRequestModel = csSerialize.PayResultRequestModel(body_json);

                    if (!string.Equals(notPayRequestModel.cateid, "1"))
                    {
                        CommonBLL.WriteLog("通知医院支付结果，业务类型：\r\n" + notPayRequestModel.cateid + "\r\n\r\n");
                        string json_patientUpdate = "head=" + head_json_encode + "&body=" + body_json_encode;

                        string returnStr = ChangZhiHePingBLL.Transparent(json_patientUpdate, "pay/result");
                        JObject returnObj = JObject.Parse(returnStr);// (JObject)JsonConvert.DeserializeObject(returnStr);
                        string bodyStr = returnObj["body"].ToString();

                        return ResultDecode.EncodeResult2(bodyStr);
                    }
                    else
                    {
                        //支付结果通知
                        payResultResponseItemModel = SearchBLL.PayResult_CZHP_New2(notPayRequestModel);


                        //序列化返回内容类
                        ReturnBodyJson = csSerialize.PayResultResponseItemModel(payResultResponseItemModel);

                        //返回参数日志
                        CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "通知医院支付结果返回参数：\r\n" + CommonBLL.ConvertJsonString(ReturnBodyJson.ToString()));
                        done = true;
                        return ResultDecode.EncodeResult(ReturnBodyJson);
                    }
                }
                else
                {
                    string body_json = CommonBLL.RequestGetParam("body").ToString();
                    body_json = Base64.DecodeBase64(body_json);
                    PayResultRequstModel notPayRequestModel = csSerialize.PayResultRequestModel(body_json);
                    PayResultResponseItemModel payResultResponseItemModel = new PayResultResponseItemModel();
                    payResultResponseItemModel.code = "-2000";
                    payResultResponseItemModel.msg = "访问频繁，请稍候重试。";
                    //序列化返回内容类
                    ReturnBodyJson = csSerialize.PayResultResponseItemModel(payResultResponseItemModel);

                    //返回参数日志
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "访问频繁，请稍候重试。" + body_json);

                    //加密返回内容Json
                    return ResultDecode.EncodeResult(ReturnBodyJson);
                }
            }
        }


        [HttpPost]
        /// <summary>
        /// 退费
        /// </summary>
        /// <param name="any"></param>
        /// <returns></returns>
        public EncodeModel refund(NameValueCollection any)
        {
            try
            {
                //获取JSON加密参数
                string jsonData = CommonBLL.RequestGetParam("jsonData").ToString();

                //解密头和内容信息
                string head_json = "";
                string body_json = "";
                head_json = CommonBLL.RequestGetParam("head").ToString();
                body_json = CommonBLL.RequestGetParam("body").ToString();
                string json_patientUpdate = "head=" + head_json + "&body=" + body_json;

                string returnStr = CommonBLL.Transparent(json_patientUpdate, "pay/refund");
                JObject returnObj = JObject.Parse(returnStr);// (JObject)JsonConvert.DeserializeObject(returnStr);
                string bodyStr = returnObj["body"].ToString();
                bodyStr = System.Web.HttpUtility.UrlEncode(bodyStr);
                CommonBLL.WriteLog(string.Format("新接口透传，UrlEncode: \r\n{0}\r\n", bodyStr));
                return ResultDecode.EncodeResult2(bodyStr);
            }
            catch (Exception err)
            {
                //序列化返回内容类
                string ReturnBodyJson = err.Message;
                //加密返回内容Json
                return ResultDecode.EncodeResult(ReturnBodyJson);
            }
        }
    }
}
